package org.idontknow.primegen;

import java.lang.Math;
import java.io.*;

/**
 * program to generate a Prime table, the upper bound is 
 * given by a command line parameter
 *
 * @author ZHAO Xinyu, Aug 4, 2006
 */

class PrimeGen {

  static int upperBound = 100;

  /**
   * method to generate all prime numbers less than upperBound, defaut
   * value 100 
   *
   * @param upperBound seems not to be too large, cuz my memery size is...
   */
  
  public static void main(String [] args) {

    FileOutputStream out;
    PrintStream p;

    if(args.length != 0)
      upperBound = Integer.parseInt(args[0]);

    //algorithm: sieve of Eratosthenes
    
    int[] sieve = new int[upperBound];
    int count = 0;

    for (int i = 2; i < upperBound; i++)
      sieve[i] = 1;

    for (int i = 2; i < Math.sqrt(upperBound); i++) {
      if(sieve[i] == 1) {
        for (int j = i; j + i < upperBound; j += i)
          sieve[j + i] = 0;
      }
    }

    //output to a file

    try{
      out = new FileOutputStream(System.getProperty("user.dir") + File.separator + "output" + File.separator + "prime_table");
      p = new PrintStream(out);

      for (int i = 1; i < upperBound; i++)
        if(sieve[i] == 1) {
          count++;
          p.printf("%8d", i);
//          p.print(i + " ");
          if(count%10 == 0)
            p.print("\n");
        }
      p.close();
      System.out.println(count);
    }catch(Exception e){
      System.err.println("error writting to file!");
    }
  }
}
